/* eslint-disable no-underscore-dangle */
import React from "react";
import { Spin, notification } from "antd";
import { Value } from "@design/core";
import { fetchForm } from "@service/form";
import messages from "@i18n/messages";
import intl from "react-intl-universal";
import FormDesigner from "./lib/index";

export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      desktopValue: undefined,
      mobileValue: undefined,
      loading: false,
      metaValue: [],
    };
  }

  componentWillMount() {
    this._mounted = false;
  }

  async componentDidMount() {
    this._mounted = true;
    this.setState({
      loading: true,
    });
    try {
      // eslint-disable-next-line no-unused-vars
      const [ _, __, params ] = window.location.pathname.split("/");
      let response = null;
      if (params) {
        response = await fetchForm();
      } else {
        return;
      }
      if (!this._mounted && response) {
        return;
      }
      document.title = response.data.name;
      const desktop = response.data.showPcFormJson;
      const mobile = response.data.showMobileFormJson;
      const metaData = response.data;
      if (desktop) {
        const desktopValue = Value.create(desktop);
        this.setState({
          desktopValue,
        });
      }
      if (mobile) {
        const mobileValue = Value.create(mobile);
        this.setState({
          mobileValue,
        });
      }
      if(metaData) {
        this.setState({
          metaValue: metaData,
        });
      }
    } catch (err) {
      notification.error({
        message: intl.get(messages.errorNotification.editorValue.id),
        description: `${intl.get(messages.errorNotification.errorText.id)}: ${
          err.message
        }`,
      });
    } finally {
      this.setState({
        loading: false,
      });
    }
  }

  onChange = ({ value }, platform) => {
    switch (platform) {
      case "mobile":
        this.setState({
          mobileValue: value,
        });
        break;
      case "desktop":
        this.setState({
          desktopValue: value,
        });
        break;
      case "metaData":
        this.setState({
          metaValue: value,
        });
        break;
      default:
        break;
    }
  };

  render() {
    const { desktopValue, mobileValue, loading, metaValue } = this.state;
    return (
      <Spin spinning={loading}>
        <FormDesigner
          desktopValue={desktopValue}
          mobileValue={mobileValue}
          metaValue={metaValue}
          onChange={this.onChange}
        />
      </Spin>
    );
  }
}
